<template>
    <div class="img-uploader">
        <label title="选择文件">
            <div class="trigger">
                <i v-if="loading" class="el-icon-loading"></i>
                <i v-if="!loading && !value" class="el-icon-plus"></i>
                <img v-if="!loading && value" :src="value" />
            </div>
            <input
                class="uploader"
                ref="uploader"
                accept="image/*"
                type="file"
                @change="handChange"
            />
        </label>
    </div>
</template>

<script>
import { upload } from "@/api/common"

export default {
    name: "ImgUploader",
    props: {
        value: {
            required: true,
        },
    },
    data() {
        return {
            loading: false
        };
    },
    methods: {
        handChange(e) {
            const file = e.target.files[0];
            console.log('file', file)
            if (!file) return;
            const typeList = ["image/jpeg", "image/png", "image/gif"];
            if (typeList.indexOf(file.type) < 0) {
                return this.$message.error("请上传jpg、png或gif格式的图片");
            }
            this.upload(file);
        },
        async upload(file) {
            this.loading = true;
            const params = new FormData()
            params.append('file', file)
            try {
                const { errno, data } = await upload(params);
                this.loading = false;
                if (errno === 0) {
                    this.$emit("input", data);
                    return
                }
            } catch (err) {
                this.loading = false;
                console.log("err", err);
            }
            this.$message.error("上传失败");
        },
    },
};
</script>

<style lang="scss" scoped>
.img-uploader {
    position: relative;
    width: 120px;
    height: 120px;
    border: 1px dashed #eaeaea;
    border-radius: 5px;
    &:hover {
        border-color: #1890ff;
    }
    .uploader {
        display: none;
    }
    .trigger {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        i {
            font-size: 30px;
            color: #666;
        }
        img {
            display: block;
            width: 100%;
            height: 100%;
            object-fit: contain;
        }
    }
}
</style>